# coding: utf-8 -*-
# author: 梁开孟
# date：2021/10/17 0017 22:32

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

pd.set_option('display.width', 180)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', 100)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


def category_pos_ratio(data, field, target,
                       sample=8, ind=8, col=6,
                       save=False, dpi=400,
                       inche="tight")->dict:
    """
    :param data: 数据帧
    :param field: 字段名称
    :param target: 目标名称
    :param sample: 最大枚举值个数，默认为8
    :param ind: 图形的长，默认为8
    :param col: 图形的宽，默认为6
    :param save: 保存的标签，默认为False，不保存
    :param dpi: 分辨率为400
    :param inche: 紧凑程度，默认为tight
    :return: dict
    """
    print("{}各个枚举值对正例样本的占比：".format(field))
    unique_count = len(data[field].unique())
    if unique_count <= sample:
        plt.figure(figsize=(ind, col))
        title = "{} VS {}".format(field, target)
        plt.title(title)
        sns.countplot(field, hue=target, data=data)
        if save:
            plt.savefig(title + ".jpg", dpi=dpi, bbox_inches=inche)
        plt.show()

    postive_rate_set = {}
    for item in data[field].unique().tolist():
        rate = round(data[data[field] == item].groupby([target])[field].count()[1] / len(data) * 100, 2)
        postive_rate_set[item] = "{}%".format(rate)
    # postive_rate_set = sorted(postive_rate_set.items(), key=lambda x: x[1], reverse=False)
    return postive_rate_set


# if __name__ == "__main__":
#     file = "data/train.csv"
#     data = pd.read_csv(file)
#     for i in ["is_married", "city", "region", "house_ownership", "car_ownership", "profession"]:
#         print(category_pos_ratio(data, i, "label"))